//
//  ViewController.swift
//  LXMoyaHelper
//
//  Created by lxpray@163.com on 08/04/2021.
//  Copyright (c) 2021 lxpray@163.com. All rights reserved.
//

import UIKit
import LXMoyaHelper
import Moya
import RxSwift
import SwiftyRSA
import LXExtensions

class ViewController: UIViewController {
    
    @IBOutlet weak var lab1: UILabel!
    
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    @IBOutlet weak var lab2: UILabel!
    @IBOutlet weak var lineBottom: NSLayoutConstraint!
    let disposeBag = DisposeBag()
    let publicKey =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFxHstCYtfuKYkynYBkfTn0cKDPFSpJLNX9RFDXr/xJQ702WWD0ORgk/NtLoBkDWpAvE7euXYWlPz2LNg9XsXioBM6rh1yjFvGxEkpSuniYTaqyPEFKuJ3s3KjgvFo1nAwVaiJqIRlawIgxshWpAMFipkUn/a86VlvQE/u6ft8WQIDAQAB"
        
    let privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOq+rvNLOKrg5GpIeXrCL7SMqHTU5JlpMFhE61BYALv4LYGMm/cdBWqZWTiYzZ26Bjvl3WmuvdV77FLh86rQOjU0Jt/BPCD0TKf8U7JR+64XdqDUJ+/l93R/qRkocFmxutkyZLF00QjglsO4UELZ4L9R4MXAvg5kWqakwekrQe7VAgMBAAECgYEA5lI9ebz+VrrdomKFvqq0/+NajXcs7FDG/HRypZwS7Fsu2wNJLAavf84COoPCitUwtKhuu/iVjddPImtMFvbDg/scx/h5UDhQsvEXbCFVGOG4SmiEKYjWP7iOBw3sHyxKIJOyFY9Uz4TM2ei0tUwXpBEHF7WHerxRG+1S/z2Gi0ECQQD27nMqszrzlx2HB8ZHQTJtKLmPtcEcc3kFog41jcPkUPkU+4FYutNrAcCTSiOLUQGLmUSMKosmNor/GgBphyNtAkEA812o/nSLMVkTfg3FOuNmsF/+VtpWzWbu5JDXk0yoALv0584hbeg9BGcVCbfiKw2kf8Z+mWRJVTNrNLiaqspwCQJBAI06ph3W8rGdTWMMfEgGrvul3jOmhXNrS91/6VaR5WcxNLTegAUqnX7HOshDD/8/bn3URFNShdFuQqNS0MeKZiUCQFsCH3xooNTndr6g76zB9VjnzPk11VgishuPfs560CjWIRO+pgmv24GV+uwTc+SdyXJvDFDYjAPsop6omk5cPeECQDNf1oigvU2dEs5TzhVFlWHJZNaslpeDPJp+oul1CkVZ2nLM1TzBPSMuO4bgRBYuHXf0SHUnDbogM72V43Cmwbs="

    let aesKey = "sMaQUrkeSXipvzAg"
    let aesIv = "StuNkPgJrXNpKuXz"
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print(lab1.lx_height)
        print(lab1.font.ascender)
        print(lab1.font.pointSize)
        print(lab1.font.descender)
        print(lab1.font.leading)

        print(lab2.lx_height)
        print(lab2.font.ascender)
        print(lab2.font.pointSize)
        print(lab2.font.descender)
        print(lab2.font.leading)

    }
    override func viewDidLoad() {
        super.viewDidLoad()
//        lab1.baselineAdjustment = .none
//        lab2.baselineAdjustment = lab1.baselineAdjustment
        bottomCons.constant = lab1.font.descender - lab2.font.descender
        lineBottom.constant = -lab2.font.leading

        // Do any additional setup after loading the view, typically from a nib.
        let dic: [String : Any] = [
            "brand": "apple",
            "simOperator": "",
            "language": "zh-Hans-CN",
            "appName": "埋点swiftDemo",
            "display": "375.0*812.0",
            "createTime": 1628217169480.614,
            "appVersionName": "1.0.1",
            "sdkVersion": "1.0.0",
            "systemVersion": "14.5",
            "packageName": "org.cocoapods.demo.YKBuryPoint-Example",
            "platform": "iOS",
            "userType": 2,
            "appVersionNo": "010001",
            "manufacturer": "apple",
            "channel": "test",
            "networkType": "WIFI",
            "deviceId": "654321",
            "model": "iPhone",
            "appCode": "10001"
        ]
        
        LXNetManager.config.normalHeaders = [
            "Content-Type":"application/json",
            "appKey" : "tgeb4okn8d9ockwx56ja8kfdsxxuntjdt7x17t2gz13qkg6z7ukq0rw9zeiz327f"
        ]
        LXNetManager.config.timeoutIntervalForRequest = 15
        print("aesKey => \(aesKey)")
        print("aesIv => \(aesIv)")
        let aesKeyEncyrpt = self.rsaEncrypt(parmas: aesKey + "###" + aesIv) ?? ""
        print("aesKeyEncyrpt => \(aesKeyEncyrpt)")
        print("解密 => \(self.decrypt(parmas: aesKeyEncyrpt))")

        let encyrptStr = self.aesEncrypt(parmas: [dic]) ?? ""
        print("encyrptStr => \(encyrptStr)")
        print("decyrptStr => \(self.aesDecrypt(parmas: encyrptStr))")

        let params: [String: Any] = [
            "encryptStr":encyrptStr,
            "dataKey":aesKeyEncyrpt
        ]
        
        let arr:[Any] = [["message": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNQFsyJ1Mvl9Ii4qg8ydA4H210rSG+9J1ADrORFLOywfZI4WcxNdMSd//y6phMIUZ8vo0lJUw+5Ks/0UllZHCQK3IZ+S7U5p77vosngKNIQxNjKYyUhB5AaYlDSWanl/qCzb/1YlNaUtkUOED/fFhjnYXgJwKCQlNdRyR4zOepEwIDAQAB", "code": "200", "timestamp": "1628651572552", "result": "<null>", "success": "1"],["message": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNQFsyJ1Mvl9Ii4qg8ydA4H210rSG+9J1ADrORFLOywfZI4WcxNdMSd//y6phMIUZ8vo0lJUw+5Ks/0UllZHCQK3IZ+S7U5p77vosngKNIQxNjKYyUhB5AaYlDSWanl/qCzb/1YlNaUtkUOED/fFhjnYXgJwKCQlNdRyR4zOepEwIDAQAB", "code": "200", "timestamp": "1628651572552", "result": "<null>", "success": "1"],["message": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNQFsyJ1Mvl9Ii4qg8ydA4H210rSG+9J1ADrORFLOywfZI4WcxNdMSd//y6phMIUZ8vo0lJUw+5Ks/0UllZHCQK3IZ+S7U5p77vosngKNIQxNjKYyUhB5AaYlDSWanl/qCzb/1YlNaUtkUOED/fFhjnYXgJwKCQlNdRyR4zOepEwIDAQAB", "code": "200", "timestamp": "1628651572552", "result": "<null>", "success": "1"]]
        let models = try? LXResultModel.map(from: arr) ?? []
        print(models)

//        LXNet(baseUrl: "http://bigdata.yocyx.com/BigDataSDK/api/v1/")
//            .path("sdk/appRsaDeviceLog")
//            .method(.post)
//            .task(.post(params: params))
//            .rx.startRequest()
//            .mapJSON()
//            .subscribe { pr in
//                print(pr)
//            } onError: { err in
//                print(err)
//            }.disposed(by: disposeBag)

    }
    func rsaEncrypt(parmas:Any) -> String? {
        do {
            var data: Data!
            if let data1 = parmas as? Data {
                data = data1
            }else if let str = parmas as? String {
                data = str.data(using: .utf8)!
            }else {
                data = try JSONSerialization.data(withJSONObject: parmas, options: .fragmentsAllowed)
            }
            let publicKeyDER = try LXKeyConvert.PublicKey.pemToPKCS8DER(publicKey)
            let encryptData = try LXCC.RSA.encrypt(data, derKey: publicKeyDER, tag: Data(), padding: .oaep, digest: .sha1)
            let encryptStr = encryptData.base64EncodedString()
            return encryptStr
        } catch let err {
            print("加密失败 \(err.localizedDescription)")
        }
        return nil
    }
    
    func aesEncrypt(parmas:Any) -> String? {
        do {
            var data: Data!
            if let data1 = parmas as? Data {
                data = data1
            }else if let str = parmas as? String {
                data = str.data(using: .utf8)!
            }else {
                data = try JSONSerialization.data(withJSONObject: parmas, options: .fragmentsAllowed)
            }
            let keyData = aesKey.data(using: .utf8)!
            let iv = aesIv.data(using: .utf8)!
            let encryptData = try LXCC.crypt(.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: data, key: keyData, iv: iv)

            let encryptStr = encryptData.base64EncodedString()
            return encryptStr
        } catch let err {
            print("加密失败 \(err.localizedDescription)")
        }
        return nil
    }

    func encrypt(parmas:Any) -> String? {
        let publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ/oo0uVP+GmAhs8GCslPJalFZNCkAqk/otTBEL2h6GRAF2ZeF/H7mI6GoEMnF2mt/r5fUmobNYYJCeUEqSerx0CAwEAAQ=="
        do {
            var data: Data!
            if let data1 = parmas as? Data {
                data = data1
            }else if let str = parmas as? String {
                data = str.data(using: .utf8)!
            }else {
                data = try JSONSerialization.data(withJSONObject: parmas, options: .fragmentsAllowed)
            }
            let publicKeyDER = try LXKeyConvert.PublicKey.pemToPKCS8DER(publicKey)
            let encryptData = try LXCC.RSA.encrypt(data, derKey: publicKeyDER, tag: Data(), padding: .oaep, digest: .sha1)
            let encryptStrAfter = encryptData.base64EncodedString()
            print("encryptStrAfter => \(encryptStrAfter)")


            return encryptStrAfter
        } catch let err {
            print("加密失败 \(err)")
        }
        return nil
    }

    func encrypt2(parmas:Any) -> String? {
        let publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ/oo0uVP+GmAhs8GCslPJalFZNCkAqk/otTBEL2h6GRAF2ZeF/H7mI6GoEMnF2mt/r5fUmobNYYJCeUEqSerx0CAwEAAQ=="
        do {
            var data: Data!
            if let data1 = parmas as? Data {
                data = data1
            }else if let str = parmas as? String {
                data = str.data(using: .utf8)!
            }else {
                data = try JSONSerialization.data(withJSONObject: parmas, options: .fragmentsAllowed)
            }
            let str = String.init(data: data, encoding: .utf8)!.replacingOccurrences(of: "\\/", with: "/")
            print("加密前:\(str)")
            let publicKeyDER = try PublicKey(pemEncoded: publicKey)
            
            let clear = try ClearMessage(string: str, using: .utf8)
            let encrypted = try clear.encrypted(with: publicKeyDER, padding: .OAEP)
            let finalData = encrypted.data
            let base64String = encrypted.base64String

            print("encryptStrAfter => \(base64String)")


            return base64String
        } catch let err {
            print("加密失败 \(err)")
        }
        return nil
    }
    
    func decrypt(parmas:String) -> String {
        do {
            let publicKeyDER = try LXKeyConvert.PrivateKey.pemToPKCS1DER(privateKey)
            let data = Data.init(base64Encoded: parmas)!
            let encryptData = try LXCC.RSA.decrypt(data, derKey: publicKeyDER, tag: Data(), padding: .oaep, digest: .sha1).0
            let decryptStrAfter = String.init(data: encryptData, encoding: .utf8)!
            print("decryptStrAfter => \(decryptStrAfter)")


            return decryptStrAfter

        } catch let err {
            print("解密失败:\(err)")
        }

        
        return parmas
    }
    func decrypt2(parmas:String) -> String {
        do {
            let privateKeyDER = try PrivateKey(pemEncoded: privateKey)
            let encrypted = try EncryptedMessage.init(base64Encoded: parmas)

            let clear = try encrypted.decrypted(with: privateKeyDER, padding: .OAEP)
            let finalData = clear.data
            let base64String = clear.base64String

            print("decryptStrAfter => \(base64String)")

        } catch let err {
            print("解密失败:\(err)")
        }

        
        return parmas
    }
    
    func aesDecrypt(parmas:String) -> String? {
        do {
            guard let data = Data.init(base64Encoded: parmas) else {
                print("加密失败")
                return nil
            }
            let keyData = aesKey.data(using: .utf8)!
            let iv = aesIv.data(using: .utf8)!
            let decryptData = try LXCC.crypt(.decrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: data, key: keyData, iv: iv)
            let decryptStr = String.init(data: decryptData, encoding: .utf8)
            return decryptStr
        } catch let err {
            print("加密失败 \(err)")
        }
        return nil
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

